// frontend/src/utils/api.js
import { CONFIG } from '../config.js';

export class ApiClient {
  static async login(identifier, password) {
    try {
      const response = await fetch(`${CONFIG.API_BASE}/api/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ identifier, password })
      });
      
      const data = await response.json();
      return { ok: response.ok, data };
    } catch (error) {
      return { ok: false, data: { message: '网络错误，请稍后重试' } };
    }
  }
  
  static async register(username, email, password, platform) {
    try {
      const response = await fetch(`${CONFIG.API_BASE}/api/auth/register`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, email, password, platform })
      });
      
      const data = await response.json();
      return { ok: response.ok, data };
    } catch (error) {
      return { ok: false, data: { message: '网络错误，请稍后重试' } };
    }
  }
  
  static async fetchUserData(token) {
    try {
      const response = await fetch(`${CONFIG.API_BASE}/api/profile`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      
      const data = await response.json();
      return { ok: response.ok, data };
    } catch (error) {
      return { ok: false, data: { message: '网络错误，请稍后重试' } };
    }
  }
  
  static async fetchDashboardData(token) {
    try {
      // 获取项目统计
      const projectsResponse = await fetch(`${CONFIG.API_BASE}/api/projects`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      
      // 获取任务统计
      const tasksResponse = await fetch(`${CONFIG.API_BASE}/api/tasks`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      
      const projectsData = await projectsResponse.json();
      const tasksData = await tasksResponse.json();
      
      return {
        ok: projectsResponse.ok && tasksResponse.ok,
        data: {
          projects: projectsData,
          tasks: tasksData
        }
      };
    } catch (error) {
      return { ok: false, data: { message: '网络错误，请稍后重试' } };
    }
  }

  static async refreshAuthToken(token) {
      try {
          const response = await fetch(`${CONFIG.API_BASE}/api/auth/refresh`, {
              method: 'POST',
              headers: {
                  'Authorization': `Bearer ${token}`,
                  'Content-Type': 'application/json'
              }
          });
          
          const data = await response.json();
          return { ok: response.ok, data };
      } catch (error) {
          return { ok: false, data: { message: '刷新令牌失败' } };
      }
  }
  
  // 添加获取用户列表的方法
  static async fetchUsers(token) {
    try {
      console.log('发送获取用户列表请求，token:', token ? token.substring(0, 20) + '...' : 'null');
      const response = await fetch(`${CONFIG.API_BASE}/api/admin/users`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      
      console.log('收到响应，状态码:', response.status);
      
      let data;
      try {
        data = await response.json();
        console.log('响应数据:', data);
      } catch (parseError) {
        console.error('解析响应JSON失败:', parseError);
        data = { message: '无法解析服务器响应' };
      }
      
      return { ok: response.ok, data, status: response.status };
    } catch (error) {
      console.error('网络请求失败:', error);
      return { ok: false, data: { message: '网络错误，请稍后重试' }, status: 0 };
    }
  }
  
  // 添加切换用户状态的方法
  static async toggleUserStatus(token, userId) {
    try {
      const response = await fetch(`${CONFIG.API_BASE}/api/admin/users/${userId}/status`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      
      const data = await response.json();
      return { ok: response.ok, data };
    } catch (error) {
      return { ok: false, data: { message: '网络错误，请稍后重试' } };
    }
  }
  
  // 添加删除用户的方法
  static async deleteUser(token, userId) {
    try {
      const response = await fetch(`${CONFIG.API_BASE}/api/admin/users/${userId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      
      const data = await response.json();
      return { ok: response.ok, data };
    } catch (error) {
      return { ok: false, data: { message: '网络错误，请稍后重试' } };
    }
  }
}